package com.booth.base.interceptor;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.booth.base.model.Users;
import com.booth.base.utils.ResultStatus;
import com.jfinal.aop.Interceptor;
import com.jfinal.core.ActionInvocation;

public class AuthInterceptor
  implements Interceptor
{
  //private final List<String> flatPublicUrl = new ArrayList(Arrays.asList(new String[] {"/admin/modules/showMenu" }));
  private final List<String> flatPublicUrl = new ArrayList(Arrays.asList(new String[] { "/admin/main", "/admin/modules/showMenu","/admin/users/checkUniqueLoginName" }));

  public void intercept(ActionInvocation arg0)
  {
    HttpSession session = arg0.getController().getSession();

    Object obj = session.getAttribute("user");
    String curActionUrl = arg0.getActionKey();
    String methodName = arg0.getMethodName();
    if (methodName.toLowerCase().equals("index"))
    {
      curActionUrl = curActionUrl + "/" + methodName;
    }
    System.out.println("当前访问URL=："+curActionUrl);
    if (obj != null)
    {
      Users u = (Users)obj;
     
      if ((u.getActionUrls().contains(curActionUrl)) || (this.flatPublicUrl.contains(curActionUrl)))
      {
        arg0.invoke();
      }
      else
      {
        System.out.println("被拦截地址：Url=" + curActionUrl);
        arg0.getController().setAttr("success", Integer.valueOf(ResultStatus.NO_AUTHORITY.getCode()));
        arg0.getController().setAttr("msg", ResultStatus.NO_AUTHORITY.getMsg());
        arg0.getController().setAttr("total", Integer.valueOf(0));
        arg0.getController().setAttr("rows", "");
        arg0.getController().renderJson();
      }
    }
    else
    {
      arg0.getController().setAttr("success", Integer.valueOf(ResultStatus.NO_LOGIN.getCode()));
      arg0.getController().setAttr("msg", ResultStatus.NO_LOGIN.getMsg());
      arg0.getController().setAttr("total", Integer.valueOf(0));
      arg0.getController().setAttr("rows", "");
      arg0.getController().renderHtml(redirectLoginPage(arg0.getController().getRequest()));
//      System.out.println("==============================123==================");
//      arg0.getController().renderJsp("index.jsp");
    }
  }

  private String redirectLoginPage(HttpServletRequest request)
  {
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
    System.out.println("basePath=:"+basePath);
    StringBuffer sb = new StringBuffer();
    sb.append("<html>");
    sb.append("<head>");

    sb.append("<script type=\"text/javascript\">");
    sb.append("window.parent.document.location.href=\"" + basePath + "admin\";");
    sb.append("</script>");

    sb.append("</head>");
    sb.append("<body>");
    sb.append("</body>");
    sb.append("</html>");

    return sb.toString();
  }
}